package haizhi.fruitmall.action;

import com.github.pagehelper.PageInfo;
import haizhi.fruitmall.constant.*;
import haizhi.fruitmall.pojo.po.*;
import haizhi.fruitmall.service.IndexService;
import haizhi.fruitmall.service.OrderService;
import haizhi.fruitmall.service.UserService;
import haizhi.fruitmall.util.DateUtil;
import haizhi.fruitmall.util.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrderService orderService;

	@Autowired
	private UserService userService;

	@Autowired
	private IndexService indexService;

	/**
	 * 添加订单
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/addOrder", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map addOrder(@RequestBody Map map) {
		Map messages = new HashMap();

		// 获得相关信息
		String user_name = (String) map.get(UserMsg.USER_NAME);// 用户名
		String order_id = DateUtil.getYear(new Date())
				+ RandomUtils.generateString(9);// 生成订单id(年份+9位随机数=13位流水号)
		// 防止生成的订单编号重复
		while (orderService.getOrderByOrderId(order_id) != null) {
			order_id = DateUtil.getYear(new Date())
					+ RandomUtils.generateString(9);
		}
		Integer user_id = userService.getUserIdByUsername(user_name);// 用户id
		String ordering_time = DateUtil.formatDateByFormat(new Date(),
				DateUtil.DATETIME_FORMAT);// 订单添加时间
		String receving_id = (String) map.get(RecevingInfoMsg.RECEVING_ID); // 收货信息编号
		Float order_freight = Float.parseFloat((String) map
				.get(OrderMsg.ORDER_FREIGHT)); // 运费
		Byte order_status = new Byte((String) map.get(OrderMsg.ORDER_STATUS)); // 订单状态
		String shipment_material = (String) map.get(OrderMsg.SHIPMENT_MATERIAL); // 发票材质
		String shopper_type = (String) map.get(OrderMsg.SHOPPER_TYPE); // 消费者类型

		// 添加订单
		Orders order = new Orders();
		order.setOrderId(order_id);
		order.setOrderStatus(order_status);
		order.setUserId(user_id);
		order.setOrderFreight(order_freight);
		order.setOrderingTime(ordering_time);
		order.setShipmentMaterial(shipment_material);
		order.setShopperType(shopper_type);
		orderService.addOrder(order);

		// 为订单添加商品
		map.put(OrderMsg.ORDER_ID, order_id);
		addOrderGoods(map);

		// 为订单添加收货信息编号
		OrderReceving orderReceving = new OrderReceving();
		orderReceving.setOrderId(order_id);
		orderReceving.setRecevingId(receving_id);
		orderService.addOrderReceving(orderReceving);

		// 返回订单号
		messages.put(OrderMsg.ORDER_ID, order_id);
		return messages;
	}

	/**
	 * 为订单添加快递单号
	 * @param map
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/addOrderTrackingNum", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map addOrderTrackingNum(@RequestBody Map map, HttpSession session) {
		Map messages = new HashMap();
		String tracking_number = (String) map.get(OrderMsg.TRACKING_NUMBER);
		Orders order = new Orders();
		order.setTrackingNumber(tracking_number);
		Map trackNumMap = new HashMap();
		trackNumMap.put(OrderMsg.ORDER_ID, (String) map.get(OrderMsg.ORDER_ID));
		orderService.updateOrder(order, trackNumMap);
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 添加订单商品
	 * @param map
	 * @param order_id
	 */
	@RequestMapping(value = "/addOrderGoods", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map addOrderGoods(@RequestBody Map map) {
		Map messages = new HashMap();
		String order_id = (String) map.get(OrderMsg.ORDER_ID);
		// 为订单添加商品
		OrderGoods ogs = null;
		// 用于接收商品信息
		List<Map<String, String>> ogList = (List<Map<String, String>>) map
				.get(OrderGoodsMsg.ORDER_GOODS);
		for (Map<String, String> ogmap : ogList) {
			ogs = new OrderGoods();
			String goods_id = (String) ogmap.get(OrderMsg.GOODS_ID);
			String purchase_num = (String) ogmap
					.get(OrderGoodsMsg.PURCHASE_NUM);
			if (goods_id != null) {
				ogs.setGoodsId(Long.parseLong(goods_id));
			}
			if (purchase_num != null) {
				ogs.setPurchaseNum(Integer.parseInt(purchase_num));
			}
			ogs.setOrderId(order_id);
			orderService.addOrderGoods(ogs);
		}
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 添加订单收货信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/addRecevingInfo", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map addRecevingInfo(@RequestBody Map map) {
		Map messages = new HashMap();
		Integer user_id = (Integer) map.get(UserMsg.USER_ID); // 用户编号
		String receving_id = DateUtil.getYear(new Date()) // 收货编号
				+ RandomUtils.generateString(9);// 生成收货单id(年份+9位随机数=13位流水号)
		// 防止生成的收货单编号重复
		while (orderService.getRecevingInfoByRecevingId(receving_id) != null) {
			receving_id = DateUtil.getYear(new Date())
					+ RandomUtils.generateString(9);
		}
		RecevingInfo recevingInfo = new RecevingInfo();
		Map<String, String> rimap = (Map<String, String>) map
				.get(RecevingInfoMsg.RECEVING_INFO);

		String receving_username = (String) rimap
				.get(RecevingInfoMsg.RECEVING_USERNAME);
		String receving_address = (String) rimap
				.get(RecevingInfoMsg.RECEVING_ADDRESS);
		String receving_phone = (String) rimap
				.get(RecevingInfoMsg.RECEVING_PHONE);
		String receving_postcode = (String) rimap
				.get(RecevingInfoMsg.RECEVING_POSTCODE);
		if (receving_username != null) {
			recevingInfo.setRecevingUsername(receving_username);
		}
		if (receving_address != null) {
			recevingInfo.setRecevingAddress(receving_address);
		}
		if (receving_phone != null) {
			recevingInfo.setRecevingPhone(receving_phone);
		}
		if (receving_postcode != null) {
			recevingInfo.setRecevingPostcode(receving_postcode);
		}
		recevingInfo.setRecevingId(receving_id);
		orderService.addRecevingInfo(recevingInfo);

		// 添加用户收货信息之间的关系
		UserReceving userReceving = new UserReceving();
		userReceving.setUserId(user_id);
		userReceving.setRecevingId(receving_id);
		orderService.addUserRecevingInfo(userReceving);

		// 添加默认收货信息
		if (orderService.getRecevingInfoDefaultByUserId(user_id).size() == 0) {
			RecevingInfoDefault recevingInfoDefault = new RecevingInfoDefault();
			recevingInfoDefault.setUserId(user_id);
			recevingInfoDefault.setRecevingId(receving_id);
			orderService.addRecevingInfoDefault(recevingInfoDefault);
		}
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 删除收货信息
	 * @param map receving_id收货单id isdefault是否是默认收货信息 
	 * @return
	 */
	@RequestMapping(value = "/deleteRecevingInfo", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map deleteRecevingInfo(@RequestBody Map map) {
		Map messages = new HashMap();
		Boolean isdefault = (Boolean) map.get("isdefault"); // 是否是默认收货编号
		String receving_id = (String) map.get(RecevingInfoMsg.RECEVING_ID); // 收货编号

		if (isdefault == true) { // 如果是默认收货地址,删除用户默认收货信息
			orderService.deleteRecevingInfoDefault(receving_id);
		}
		// 删除用户与收货信息的关系
		orderService.deleteUserReceving(receving_id);
		// 删除收货信息
		orderService.deleteRecevingInfo(receving_id);
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 删除订单
	 * 	     根据订单id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/delete/{order_id}", method = RequestMethod.DELETE, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map deleteOrder(@PathVariable(OrderMsg.ORDER_ID) String order_id) {
		Map messages = new HashMap();
		// 删除订单信息
		orderService.deleteOrderById(order_id);

		// 删除订单中的商品信息
		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setOrderId(order_id);
		orderService.deleteOrderGoods(orderGoods);

		// 删除订单的收货信息
		orderService.deleteOrderReceving(order_id);
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 对某个收货信息进行修改
	 * @param map
	 * @return
	 * 
	 */
	@RequestMapping(value = "/updateReceving", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map updateReceving(@RequestBody Map map) {
		Map messages = new HashMap();
		String receving_id = (String) map.get(RecevingInfoMsg.RECEVING_ID);// 必填
		String receving_username = (String) map
				.get(RecevingInfoMsg.RECEVING_USERNAME);
		String receving_address = (String) map
				.get(RecevingInfoMsg.RECEVING_ADDRESS);
		String receving_phone = (String) map
				.get(RecevingInfoMsg.RECEVING_PHONE);
		String receving_postcode = (String) map
				.get(RecevingInfoMsg.RECEVING_POSTCODE);
		// 根据receving_id修改receving_info
		RecevingInfo recevingInfo = new RecevingInfo();
		recevingInfo.setRecevingId(receving_id);
		recevingInfo.setRecevingAddress(receving_address);
		recevingInfo.setRecevingPhone(receving_phone);
		recevingInfo.setRecevingUsername(receving_username);
		recevingInfo.setRecevingPostcode(receving_postcode);
		orderService.updateRecevingInfo(recevingInfo);
		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 为某张订单修改收货信息
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/updateRecevingInfo", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map updateRecevingInfo(@RequestBody Map map) {
		Map messages = new HashMap();
		String order_id = (String) map.get(OrderMsg.ORDER_ID);// 获取订单编号

		// 根据订单编号获取order_receving
		OrderReceving orderReceving = orderService.getOrderReceving(order_id);
		// 传入receving_id
		map.put(RecevingInfoMsg.RECEVING_ID, orderReceving.getRecevingId());

		// 修改收货信息
		updateReceving(map);

		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 通过用户id和收货编号修改默认收货信息
	 * @param map user_id用户编号 receving_id收货编号
	 * @return
	 */
	@RequestMapping(value = "/updateRecevingDefault", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map updateRecevingDefault(@RequestBody Map map) {
		Map messages = new HashMap();
		String user_id = (String) map.get(UserMsg.USER_ID);// 用户编号
		String receving_id = (String) map.get(RecevingInfoMsg.RECEVING_ID);// 收货编号
		RecevingInfoDefault recevingInfoDefault = new RecevingInfoDefault();
		recevingInfoDefault.setUserId(Integer.parseInt(user_id));
		recevingInfoDefault.setRecevingId(receving_id);
		orderService.updateRecevingDefault(recevingInfoDefault);

		messages.put(ResultConstant.RESULT, ResultConstant.SUCCESS);
		return messages;
	}

	/**
	 * 查询用户的默认收货信息
	 * @param session
	 * @return
	 */
	@RequestMapping(value = "/getRecevingInfoDefault", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map getRecevingInfoDefault(@RequestParam String user_name) {
		Map messages = new HashMap();

		// 判断用户名是否存在
		List<User> userList = userService.getUserByUserName(user_name);
		if (userList.size() == 0) {
			messages.put(ResultConstant.RESULT, UserMsg.USER_NOT_EXIST);
			return messages;
		}
		Integer user_id = userService.getUserIdByUsername(user_name);// 用户id
		List<RecevingInfoDefault> recevingInfoDefaultList = orderService
				.getRecevingInfoDefaultByUserId(user_id);
		if (recevingInfoDefaultList.size() == 0) {
			messages.put(ResultConstant.RESULT,
					RecevingInfoMsg.NO_ANY_RECEVINGINFO_DEFAULT);
			return messages;
		} else {
			RecevingInfo recevingInfo = orderService
					.getRecevingInfoByRecevingId(recevingInfoDefaultList.get(0)
							.getRecevingId());
			messages.put(ResultConstant.RESULT, recevingInfo);
		}
		return messages;
	}

	/**
	 *  通过某个订单号获得该订单所拥有的商品信息
	 * @param order_id
	 * @return
	 */
	public List<Map<String, Object>> getGoodsOfOneOrderById(String order_id) {
		// 根据order_id获取所有的商品id
		List<OrderGoods> orderGoods = orderService
				.getOrderGoodsByOrderId(order_id);

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> goodsAndGoodsparamsMap = null;
		for (OrderGoods orderGood : orderGoods) {
			Long goodsId = orderGood.getGoodsId();
//			GoodsParamVO goodsParamVO = indexService.getGoodsParams(goodsId);
			goodsAndGoodsparamsMap = new HashMap<String, Object>();

			goodsAndGoodsparamsMap.put(OrderGoodsMsg.PURCHASE_NUM,
					orderGood.getPurchaseNum());
//			goodsAndGoodsparamsMap.put("goods_and_param", goodsParamVO);

			list.add(goodsAndGoodsparamsMap);
		}
		return list;
	}

	/**
	 *  通过订单id获取商品信息
	 * @return
	 */
	@RequestMapping(value = "/getGoods/{order_id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map getGoodsOfOrderByOrderId(
			@PathVariable("order_id") String order_id) {
		Map messages = new HashMap();
		// 封装一个订单的商品信息
		List<Map<String, Object>> list = getGoodsOfOneOrderById(order_id);
		// 根据订单id获取订单信息
		Orders order = orderService.getOrderByOrderId(order_id);
		messages.put(OrderMsg.ORDER, order);
		messages.put(ResultConstant.RESULT, list);
		return messages;
	}

	/**
	 * 查询某个用户的订单信息（可根据订单状态来查询）
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/getPageInfoByUserName", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map getPageInfoByUserName(@RequestParam Map map) {
		Map messages = new HashMap();
		int currentPage = Integer.parseInt((String) map
				.get(PageInfoMsg.CURRENT_PAGE));
		int pageSize = Integer
				.parseInt((String) map.get(PageInfoMsg.PAGE_SIZE));
		String user_name = (String) map.get(UserMsg.USER_NAME);// 用户名
		Byte order_status = null; // 订单状态
		String orderStatus = (String) map.get(OrderMsg.ORDER_STATUS);
		if (orderStatus != null) {
			order_status = new Byte(orderStatus);
		}

		// 判断用户是否存在
		List<User> userList = userService.getUserByUserName(user_name);
		if (userList.size() == 0) {
			messages.put(ResultConstant.RESULT, UserMsg.USER_NOT_EXIST);
			return messages;
		}

		Integer user_id = userService.getUserIdByUsername(user_name);
		PageInfo pageInfo = orderService.getPageInfoOfOrderByUserName(user_id,
				order_status, currentPage, pageSize);

		messages.put("currentpage", pageInfo.getPageNum());
		messages.put("page_size", pageInfo.getPageSize());
		messages.put("total_pages", pageInfo.getPages());
		List<Orders> ordersList = pageInfo.getList();
		System.out.println(ordersList.size());

		// 封装一个用户的所有订单信息
		List<Map<String, Object>> allOrderInfoOfOneUser = new ArrayList<Map<String, Object>>();
		// 封装某个订单的所有信息
		Map<String, Object> OneOrderInfo = null;
		for (Orders orders : ordersList) {
			OneOrderInfo = new HashMap<String, Object>();
			List<Map<String, Object>> list = getGoodsOfOneOrderById(orders
					.getOrderId());

			// 封装一个订单的所有商品的list
			OneOrderInfo.put("goodsList", list);

			// 封装order的map
			OneOrderInfo.put(OrderMsg.ORDER, orders);

			allOrderInfoOfOneUser.add(OneOrderInfo);
		}
		messages.put("order_info", allOrderInfoOfOneUser);
		return messages;
	}

	@RequestMapping(value = "/getRecevingInfoByUserName/{user_name}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Map getRecevingInfoByUserName(
			@PathVariable("user_name") String user_name) {
		Map messages = new HashMap();

		// 根据用户名获取用户id
		Integer user_id = userService.getUserIdByUsername(user_name);

		// 获取用户收货信息的关系
		List<UserReceving> userRecevings = orderService
				.getUserRecevingByUserId(user_id);

		if (userRecevings.size() == 0) {
			messages.put(ResultConstant.RESULT, ResultConstant.NULL);
			return messages;
		}

		// 用于保存所有收货信息
		List<Map<String, Object>> recevingInfos = new ArrayList<Map<String, Object>>();
		Map<String, Object> recevingInfoMap = null;
		// 通过receving_id查询收货信息
		for (UserReceving userReceving : userRecevings) {
			recevingInfoMap = new HashMap<String, Object>();
			RecevingInfo recevingInfo = orderService
					.getRecevingInfoByRecevingId(userReceving.getRecevingId());
			recevingInfoMap.put(RecevingInfoMsg.RECEVING_INFO, recevingInfo);
			recevingInfos.add(recevingInfoMap);
		}

		messages.put(ResultConstant.RESULT, recevingInfos);
		return messages;
	}

}
